<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所属企业">
          <a-select
            show-search
            placeholder="请选择一个企业"
            option-filter-prop="children"
            :filter-option="filterOption"
            v-decorator="['enterpriseId', {}]"
            @change="handleChange2"
          >
            <a-select-option
              v-for="(item, index) in enterprise"
              :key="index"
              :value="item.id"
            >{{ item.enterpriseName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售顾问身份证号">
          <a-input placeholder="请输入销售顾问身份证号" v-decorator="['salesPin', {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售顾问姓名">
          <a-input placeholder="请输入销售顾问姓名" v-decorator="['salesName', {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售顾问电话">
          <a-input placeholder="请输入销售顾问电话" v-decorator="['salesPhone', {}]" />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售顾问入职时间">
          <a-date-picker
            style="width: 100%"
            :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
            format="YYYY-MM-DD HH:mm:ss"
            v-decorator="[
              'hireDate',
              {},
              //{rules: [{ required: false, message: '请输入入职时间!' }]},
            ]"
            :showTime="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
            :disabledDateTime="disabledDateTime"
            placeholder="请选择时间"
            @change="onChange"
            @ok="onOk"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="工号">
          <a-input placeholder="请输入工号" v-decorator="['salesCode', {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否在岗">
          <template>
            <a-radio-group v-decorator="['isInvalid', validatorRules.isInvalid]" placeholder="是否在岗">
              <a-radio value="1">在岗</a-radio>
              <a-radio value="0">离岗</a-radio>
              <a-radio value="2">转岗</a-radio>
            </a-radio-group>
          </template>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售顾问照片">
          <a-upload
            name="file"
            enctype="multipart/form-data"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="importImgAction"
            :headers="headers"
            :data="picData"
            :before-upload="beforeUpload"
            @change="handleChange"
            v-decorator="['salesPic', {}]"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="file" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传照片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务范围">
          <a-select placeholder="请选择" v-decorator="['bizScope', {}]">
            <a-select-option value="1">新车</a-select-option>
            <a-select-option value="2">二手车</a-select-option>
            <a-select-option value="3">新车+二手车</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { cxmEnterpriseTwo } from '@/api/api'
import pick from 'lodash.pick'
import moment from 'moment'
import JUpload from '@/components/jeecg/JUpload'
import CxmSalesInfoList from '@views/cxm/CxmSalesInfoList'
import DepartModal from '@views/cxm/modules/EnterpriseModal'
import DataLevelRef from '@comp/jeecg/DataLevelRef'
import CxmDealerRegrpModal from '@views/cxm/modules/CxmDealerRegrpModal'
import { USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import { mapActions, mapGetters, mapState } from 'vuex'
export default {
  name: 'CxmSalesInfoModal',
  components: {
    JUpload,
  },
  data() {
    return {
      title: '销售顾问',
      visible: false,
      model: {},
      enterprise: {},
      enterpriseName: '',
      dictDisabled: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/cxm/cxmSalesInfo/add',
        edit: '/cxm/cxmSalesInfo/edit',
        queryEnterprise: '/cxm/cxmEnterprise/queryEnterprise',
        imgAction: '/cxm/cxmAccessoriesContents/uploadAccessories'
      },
      loading: false,
      imageUrl: '',
      headers: '',
      picData: {
        username: this.userInfo().updateBy,
        fileType: 2
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = { "X-Access-Token": token }


  },
  mounted() {
    /* console.log(this.nickname());
    console.log(this.userInfo().updateBy); */
  },
  methods: {
    ...mapGetters(["nickname", "avatar", "userInfo"]),
    add(depart) {
      if (depart) {
        this.dictDisabled = false
      } else {
        this.dictDisabled = true
      }
      this.edit(depart)
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)

      console.log('red01', record)

      if (record != undefined && !record) {
        this.model.enterpriseId = record.enterpriseId
      }
      console.log(this.model);
      /* this.handleChange2(this.model.enterpriseId) */
      console.log(this.enterprise);
      this.enterpriseName = this.model.enterpriseName;
      this.model.hireDate = moment(this.model.hireDate);
      //获取企业信息
      this.getEnterprise()
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'enterpriseId',
            'salesPin',
            'salesCode',
            /* 'idScancopy', */
            'salesName',
            'salesPhone',
            /* 'isDeleted', */
            'isInvalid',
            /* 'isVerified', */
            /* 'ranking', */
            'hireDate',
            /* 'createUser', */
            /* 'updateUser', */
            'bizScope'
          )
        )
        //时间格式化
      })
      if (this.model.salesPic) {
        getAction('/cxm/cxmAccessoriesContents/viewAccessories', { id: this.model.salesPic }).then((res) => {
          if (res.success) {
            this.imageUrl = "data:image/" + res.result.fileFormat + ";base64," + res.result.fileInfos
          }
        })
      } else {
        this.imageUrl = "";
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {

      console.log(this.imageUrl);
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          console.log(formData)
          if (formData.salesPic) {
            formData.salesPic = formData.salesPic.file.response.result;
          }
          formData.enterpriseName = this.enterpriseName;
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    getEnterprise() {
      let userinfo = Vue.ls.get(USER_INFO)

      let params = {
        enterpriseId: userinfo.enterpriseId,
      }
      cxmEnterpriseTwo(params).then((res) => {
        if (res) {
          this.enterprise = res.result
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleChange2(value) {
      let id = `${value}`

      console.log('los', value)
      for (var i = 0; i < this.enterprise.length; i++) {
        if (this.enterprise[i].id == id) {

          this.enterpriseName = this.enterprise[i].enterpriseName


          return
        }
      }
    },

    //入职时间
    moment,
    onChange(value, dateString) {
      console.log('Selected Time: ', value)
      console.log('Formatted Selected Time: ', dateString)
    },
    onOk(value) {
      console.log('onOk: ', value)
    },
    range(start, end) {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    },
    disabledDateTime() {
      return {
        disabledHours: () => this.range(0, 24).splice(4, 20),
        disabledMinutes: () => this.range(30, 60),
        disabledSeconds: () => [55, 56],
      }
    },
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    },
    handleChange(info) {
      console.log(info);
      if (info.file.status === 'uploading') {
        this.loading = true;

        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
          this.loading = false;
          /*  let httpurl = this.url.imgAction;
           let params = {
             username:this.userInfo().updateBy,
             fileType:3
           }
           let method = 'post';
           httpAction(httpurl, params, method).then((res)=>{
           console.log(res);
         }) */
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('您只能上传jpg或png格式的文件');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB');
      }
      return isJpgOrPng && isLt2M;
    },
  },
  computed: {
    importImgAction: function () {
      return `${process.env.VUE_APP_BASE_API}${this.url.imgAction}`
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-upload-select-picture-card img {
  width: 128px;
  height: 128px;
}
</style>